package com.study.concurrent;

import com.study.concurrent.atomic.AtomicIntegerTest;
import com.study.concurrent.atomic.AtomicStampedReferenceTest;

/**
 * @Name: MainTest
 * @Description: java类作用描述
 * @Author: yn
 * @CreateDate: 2022/4/14 10:21
 * @Remark: 特殊说明
 * @Version: 1.0
 */
public class MainTest {
    public static void main(String[] args) {
//        AtomicIntegerTest atomicIntegerTest=new AtomicIntegerTest();
//        System.out.println(atomicIntegerTest.getCount());
//        atomicIntegerTest.increment();
//        System.out.println(atomicIntegerTest.getCount());
        AtomicStampedReferenceTest atomicStampedReferenceTest=new AtomicStampedReferenceTest();
        Thread main = new Thread(() -> {
            System.out.println("操作线程" + Thread.currentThread() +",初始值 a = " + atomicStampedReferenceTest.getCount());
            int stamp = atomicStampedReferenceTest.getStamp(); //获取当前标识别
            try {
                Thread.sleep(1000); //等待1秒 ，以便让干扰线程执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean isCASSuccess = atomicStampedReferenceTest.atomicStampedReference.compareAndSet(atomicStampedReferenceTest.getCount(),
                    atomicStampedReferenceTest.getCount()+1,
                    stamp,
                    stamp+1);;  //此时expectedReference未发生改变，但是stamp已经被修改了,所以CAS失败
            System.out.println("操作线程" + Thread.currentThread() +",CAS操作结果: " + isCASSuccess);
        },"主操作线程");

        Thread other = new Thread(() -> {
            Thread.yield(); // 确保thread-main 优先执行
            atomicStampedReferenceTest.increment();
            System.out.println("操作线程" + Thread.currentThread() +",【increment】 ,值 = "+ atomicStampedReferenceTest.getCount());
            atomicStampedReferenceTest.increment();
            System.out.println("操作线程" + Thread.currentThread() +",【decrement】 ,值 = "+ atomicStampedReferenceTest.getCount());
        },"干扰线程");

        main.start();
        other.start();
    }
}
